<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Announce extends Controller {
	public function action_index()
	{

		$info_hash = $_GET['info_hash'];
		$info_hash = bin2hex($info_hash);


		$torrent = ORM::factory('torrent')
		->where('info_hash', '=', $info_hash)
		->find();

		$peer_id = $_GET['peer_id'];

		$peer = ORM::factory('peer')
		->and_where_open()
		->and_where('torrent_id','=',$torrent->id)
		->and_where('peer_id', '=', $peer_id)
		->and_where_close()
		->find();

		if (!$peer->loaded()){
			$peer = ORM::factory('peer');
			$peer->torrent_id = $torrent->id;
			$peer->peer_id = $peer_id;
		}

		$peer->ip = $_SERVER['REMOTE_ADDR'];
		$peer->port = $_GET['port'];
		$peer->lastseen = time();
		if ($_GET['left'] == 0){
			$peer->seeder = 1;
		}

		$peer->save();



		function benc_str($s) {
			return strlen($s) . ":$s";
		}

		$seeders = ORM::factory('peer')
		->where('torrent_id','=',$torrent->id)
		->find_all();

		$compact = (isset($_GET ['compact']));
		$resp = 'd' . benc_str ( 'interval' ) . 'i' . 180 . 'e' . benc_str ( 'peers' ) . ($compact ? '' : 'l');
		$no_peer_id = ($_GET ['no_peer_id'] == 1);
		$plist = '';
		foreach ($seeders as $seeder){
			if ($compact) {
				$peer_ip = explode ( '.', $seeder->ip );
				$plist .= pack ( "C*", $peer_ip [0], $peer_ip [1], $peer_ip [2], $peer_ip [3] ) . pack ( "n*", ( int ) $seeder->port );
			} else {
				$resp .= 'd' . benc_str ( 'ip' ) . benc_str ( $seeder->ip ) . (! $no_peer_id ? benc_str ( "peer id" ) . benc_str ( $seeder->peer_id ) : '') . benc_str ( 'port' ) . 'i' . $seeder->port . 'e' . 'e';
			}
		}
		$resp .= ($compact ? benc_str ( $plist ) : '') .  "ee";

		
			@header ( "Content-Type: text/plain" );
			@header ( "Pragma: no-cache" );
			print ( $resp );





		$deads = ORM::factory('peer')
		->where('lastseen','<',time()-3600)
		->find_all();
		foreach ($deads as $dead) {
			$dead->delete();
		}
	}
}